from datetime import datetime

from device import DeviceBase
from .button import Button

class TaskAtom:
    def __init__(self, interface_name:str, task_name:str, button_name_list:list[str]):
        self.interface_name = interface_name
        self.task_name = task_name
        self.button_name_list = button_name_list

    def run(self, button_dict:dict[str, Button]):
        for button_name in self.button_name_list:
            if button_name not in button_dict.keys():
                raise ValueError(f"Button {button_name} not found in button_dict")
            print('tap', button_name)
            button_dict[button_name].tap()

class TaskBase:
    def __init__(self, task_name:str, base_priority:int=1, taskatom_list:list[TaskAtom]=[]):
        self.task_name = task_name
        self.next = 0#用于记录下一个需要执行的原子任务，便于调度
        self.base_priority = base_priority  # 初始优先级
        self.current_priority = base_priority  # 当前优先级，可被动态调整，高优先级优先。0表示休眠
        self.taskatom_list = taskatom_list

    def run(self, button_dict:dict[str, Button]):
        '''
        可能会导致任务的下一步执行(如果需要)，可能会更新current_priority
        '''
        raise NotImplementedError()

    def is_complete(self) -> bool:
        '''
        已完成的任务将被踢出队列
        '''
        raise NotImplementedError()

    def is_activated(self) -> bool:
        return self.current_priority != 0

    def update_state(self) -> None:
        """更新当前状态"""
        raise NotImplementedError()
    
    def get_interface_name(self) -> str:
        return self.taskatom_list[self.next].interface_name

class RegularTask(TaskBase):
    '''
    在固定时间激活的任务
    '''
    def __init__(self, task_name, base_priority = 1, task_list = []):
        super().__init__(task_name, base_priority, task_list)
        self.activate_time = datetime.now()#任务的下一次激活时间，用于调度

    def update_state(self) -> None:
        """尝试根据当前时间更新优先级"""
        if (datetime.now() - self.activate_time).total_seconds() >= 0:
            '''激活时间已过'''
            self.current_priority = self.base_priority